import React, { Suspense } from 'react';
import PageLoading from '@/components/PageLoading';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import { Button, Card, Col, DatePicker, Form, Icon, Input, Select, Table, TimePicker, Menu, Dropdown, Checkbox, Pagination } from 'antd';
import { connect } from 'dva';
import moment from 'moment';
import styles from './index.less';
import { getSessionRecordsList, getSessionContext, exportSessionList, getTenantAll, getRobotList } from '@/services/datastatistics';
import { doRobotList } from '@/services/robotManagement';
import ContextModal from '@/utils/contextModal';
import { getAgentList } from '@/services/assistantCenter';
import { getAssistantList } from '@/services/digitalEmployees';

const InputGroup = Input.Group;
const { Option } = Select;

class SessionRecords extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tenantList: [],
      applyList: [],
      queryData: {
        tenantId: undefined,
        applicationId: '0',
        timeType: 0,
        current: 1,
        size: 10,
        fromDate: '',
        toDate: '',
        search: '',
        channel:null
      },
      list: [],
      total: 0,
      loading: true,
      contextModalVisible: false,
      contextMessage: [],

      visible: false,
      isTableTab: {
        id: true,
        title: true,
        userId: true,
        type: true,
        applicationName: true,
        createTime: true,
        updateTime: true,
        suggestion: true,
        timeLength: true,
        answerCount: true,
        username:true,
        channel:true,
        sessionType:true,
        agentName:true
      },
      agentList:[]
    };
    this.columns = [
      {
        title: '用户',
        dataIndex: 'userId',
        key: 'userId',
        width: 180
      },
      {
        title: '名称',
        dataIndex: 'username',
        key: 'username',
        width: 180
      },
      {
        title: '会话名称',
        dataIndex: 'title',
        key: 'tile',
        width: 220,
      },
      {
        title: '渠道',
        dataIndex: 'channel',
        key: 'channel',
        width: 220,
      },
      {
        title: '会话类型',
        dataIndex: 'sessionType',
        key: 'sessionType',
        width: 180,
        render:(sessionType) => {
          switch(sessionType){
            case 0:
              return '对话问答'
            case 1:
              return '文档问答'
            case 2:
              return '助手问答'
            case 3:
              return 'AI咨询师'
          }
        }
      },
      {
        title: 'AI咨询师名称',
        dataIndex: 'agentName',
        key: 'agentName',
        width: 220,
      },
      {
        title: '发起时间',
        dataIndex: 'createTime',
        key: 'createTime',
        width: 180,
        render: text => {
          if (text) {
            return moment(text).format('YYYY-MM-DD HH:mm:ss');
          }
        }
      },
      {
        title: '更新时间',
        dataIndex: 'updateTime',
        key: 'updateTime',
        width: 180,
        render: text => {
          if (text) {
            return moment(text).format('YYYY-MM-DD HH:mm:ss');
          }
        }
      },
      {
        title: '问答次数',
        dataIndex: 'answerCount',
        key: 'answerCount',
        width: 100,
      },
      {
        title: '应用',
        dataIndex: 'applicationName',
        key: 'applicationName',
        width: 150
      },
      {
        title: '会话ID',
        dataIndex: 'id',
        key: 'id',
        width: 200
      },
      {
        title: '操作',
        width: 150,
        fixed: 'right',
        align: 'center',
        render: (text, row, index) => {
          return <Button type={'primary'} onClick={() => this.getChatRecords(row)}>上下文</Button>
        }
      },
    ];
  }

  componentWillMount() {
    let { queryData } = this.state;
    const fromDate = moment().subtract("1", "months").format('YYYY-MM-DD');
    const toDate = moment().format('YYYY-MM-DD');
    queryData.fromDate = fromDate;
    queryData.toDate = toDate;
    this.setState({ queryData });
  }

  componentDidMount() {
    this.getList();
    const { currentUser } = this.props;
    if (currentUser.tenantId === '2') {
      this.getTenant();
    } else {
      this.getApply();
    }
  }

  /**
   * 获取所有机器人（作为筛选条件）
   */
  getTenant = async () => {
    let res = await getTenantAll();
    this.setState({ tenantList: res }, () => this.getRobot(null));
  };
  getRobot = async (value) => {
    if (value && value !== '0') {
      let res = await getRobotList({ tenantId: value });
      this.setState({ applyList: res });
    } else {
      this.setState({ applyList: [] }, () => {
        this.props.form.setFieldsValue({ "applicationId": '0' })
      });
    }
  };
  getApply = async () => {
    let res = await doRobotList({ current: 1, size: 999999 });
    console.log(res);
    this.setState({ applyList: res, });
  };
  getList = () => {
    const { queryData } = this.state;
    this.setState({ loading: true }, async () => {
      if(this.props.currentUser.applicationId){
        queryData.applicationId = this.props.currentUser.applicationId
      }
      const res = await getSessionRecordsList(queryData)
      this.setState({ loading: false, list: res.records, total: res.total })
    })
  }

  /**
   * 根据条件查询
   * @returns {*}
   */
  queryByCondition = () => {
    let { queryData } = this.state;
    let formInfo = this.props.form.getFieldsValue();
    queryData.fromDate = formInfo.time[0].format('YYYY-MM-DD');
    queryData.toDate = formInfo.time[1].format('YYYY-MM-DD');
    queryData.timeType = formInfo.timeType;
    queryData.tenantId = formInfo.tenantId ? formInfo.tenantId : undefined;
    queryData.applicationId = formInfo.applicationId ? formInfo.applicationId : '0';
    queryData.sessionType = formInfo.sessionType;
    queryData.current = 1;
    queryData.search = formInfo.search;
    queryData.channel = formInfo.channel;
    if(formInfo.sessionType == 2 || formInfo.sessionType == 3){
      queryData.agentId = formInfo.agentId
    }else{
      queryData.agentId = null
    }
    this.setState({ queryData }, () => this.getList());
  }

  /**
   * 分页查询
   * @returns {*}
   */
  queryByPage = (page, size) => {
    let { queryData } = this.state;
    queryData.current = page;
    queryData.size = size;
    this.setState({ queryData }, () => this.getList());
  }

  /**
   * 获取上下文
   * @returns {*}
   */
  getChatRecords = async row => {
    const res = await getSessionContext({ sessionId: row.id });
    this.setState({ contextMessage: res, contextModalVisible: true })
  }

  /**
   * 关闭上下文
   * @returns {*}
   */
  cancelContextModal = () => {
    this.setState({ contextModalVisible: false, contextMessage: [] })
  }

  /**
   * 导出
   * @returns {*}
   */
  exportRecords = async () => {
    const { queryData } = this.state;
    const res = await exportSessionList(queryData);
  }

  handleVisibleChange = flag => {
    this.setState({ visible: flag });
  };

  onCheckboxChange = (e, type) => {
    let { isTableTab } = this.state;
    isTableTab[type] = e.target.checked;
    this.setState({ isTableTab });
  }

  //获取所有助手
  getAllAgent = async () => {
    const res = await getAgentList({search:"",current:1,size:999})
    this.setState({
      agentList:res.records ? res.records : []
    })
  }

  //获取所有AI咨询师
  getAllDigitalEmployees = async () => {
    const res = await getAssistantList()
    this.setState({
      agentList:res ? res : []
    })
  }

  changeSessionType = value => {
    this.props.form.resetFields("agentId")
    if(value == 2){
      this.getAllAgent()
    }else if(value == 3){
      this.getAllDigitalEmployees()
    }
  }

  render() {
    const { list, total, loading, queryData, contextModalVisible, contextMessage, isTableTab, applyList,agentList } = this.state;
    const { getFieldDecorator,getFieldValue } = this.props.form;
    const { currentUser } = this.props;
    const menu = (
      <Menu onClick={() => { }}>
        <Menu.Item>
          <Checkbox onChange={e => this.onCheckboxChange(e, "userId")} checked={isTableTab["userId"]}>用户</Checkbox>
        </Menu.Item>
        <Menu.Item>
          <Checkbox onChange={e => this.onCheckboxChange(e, "username")} checked={isTableTab["username"]}>名称</Checkbox>
        </Menu.Item>
        <Menu.Item>
          <Checkbox onChange={e => this.onCheckboxChange(e, "title")} checked={isTableTab["title"]}>会话名称</Checkbox>
        </Menu.Item>
        <Menu.Item>
          <Checkbox onChange={e => this.onCheckboxChange(e, "channel")} checked={isTableTab["channel"]}>渠道</Checkbox>
        </Menu.Item>
        <Menu.Item>
          <Checkbox onChange={e => this.onCheckboxChange(e, "sessionType")} checked={isTableTab["sessionType"]}>会话类型</Checkbox>
        </Menu.Item>
        <Menu.Item>
          <Checkbox onChange={e => this.onCheckboxChange(e, "agentName")} checked={isTableTab["agentName"]}>AI咨询师名称</Checkbox>
        </Menu.Item>
        <Menu.Item>
          <Checkbox onChange={e => this.onCheckboxChange(e, "createTime")} checked={isTableTab["createTime"]}>发起时间</Checkbox>
        </Menu.Item>
        <Menu.Item>
          <Checkbox onChange={e => this.onCheckboxChange(e, "updateTime")} checked={isTableTab["updateTime"]}>更新时间</Checkbox>
        </Menu.Item>
        <Menu.Item>
          <Checkbox onChange={e => this.onCheckboxChange(e, "answerCount")} checked={isTableTab["answerCount"]}>问答次数</Checkbox>
        </Menu.Item>
        <Menu.Item>
          <Checkbox onChange={e => this.onCheckboxChange(e, "applicationName")} checked={isTableTab["applicationName"]}>应用</Checkbox>
        </Menu.Item>
        <Menu.Item>
          <Checkbox onChange={e => this.onCheckboxChange(e, "id")} checked={isTableTab["id"]}>会话ID</Checkbox>
        </Menu.Item>        
      </Menu>
    );
    let columns = this.columns.filter(item => (item.dataIndex && isTableTab[item.dataIndex]) || !item.dataIndex);

    return (
      <div style={{ height: '100%' }}>
        <Suspense fallback={<PageLoading />}>
          <PageHeaderWrapper>
            <Card bodyStyle={{ padding: '0px 15px 6px', }} style={{ height: '100%' }}>
              <div className={styles.sessionRecordsListClass}>
                <Form layout={'inline'}>
                  <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '16px', }}>
                    <div>
                      {/* <Form.Item>
                        会话总数：<span style={{ fontSize: 18, fontWeight: 'bold', marginRight: 10, width: 55, display: 'inline-block' }}>{total}</span>
                      </Form.Item> */}
                      <Form.Item>
                        <InputGroup compact>
                          {getFieldDecorator('timeType', { initialValue: 0 })(
                            <Select>
                              <Option value={0}>发起时间</Option>
                              <Option value={1}>更新时间</Option>
                            </Select>
                          )}
                          {getFieldDecorator('time', {
                            initialValue: [moment().subtract("1", "months"), moment()]
                          })(
                            <DatePicker.RangePicker allowClear={false} style={{ width: '260px' }} />
                          )}
                        </InputGroup>
                      </Form.Item>
                      {currentUser.tenantId === '2' ? (
                        <Form.Item>
                          {getFieldDecorator('tenantId', { initialValue: '0' })(
                            <Select style={{ width: 150 }} placeholder={'请选择租户'} onChange={value => this.getRobot(value)}>
                              <Select.Option value='0'>全部租户</Select.Option>
                              {tenantList.map(item => {
                                return (
                                  <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                                );
                              })}
                            </Select>
                          )}
                        </Form.Item>
                      ) : null}
                      {
                        currentUser.applicationId ? null : (
                            <Form.Item>
                              {getFieldDecorator('applicationId', { initialValue: '0' })(
                                  <Select style={{ width: 120 }} placeholder={'请选择应用'}>
                                    <Select.Option value='0'>全部应用</Select.Option>
                                    {applyList.map(item => {
                                      return (
                                          <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                                      );
                                    })}
                                  </Select>
                              )}
                            </Form.Item>
                        )
                      }
                      <Form.Item>
                        {getFieldDecorator('sessionType', { initialValue: null })(
                          <Select style={{ width: 120 }} placeholder={'请选择会话类型'} onChange={this.changeSessionType}>
                            <Select.Option value={null}>会话类型</Select.Option>
                            <Select.Option value={0}>对话问答</Select.Option>
                            <Select.Option value={1}>文档问答</Select.Option>
                            <Select.Option value={2}>助手问答</Select.Option>
                            <Select.Option value={3}>AI咨询师</Select.Option>
                          </Select>
                        )}
                      </Form.Item>
                      {
                        getFieldValue("sessionType") == 2 || getFieldValue("sessionType") == 3 ? (
                          <Form.Item>
                            {getFieldDecorator('agentId', { initialValue: null })(
                              <Select style={{ width: 200 }} placeholder={'请选择'}>
                                <Select.Option value={null}>{getFieldValue("sessionType") == 2 ? '全部助手' : '全部AI咨询师'}</Select.Option>
                                {
                                  agentList.map(item => (
                                    <Select.Option value={item.id} key={item.id}>{item.name}</Select.Option>
                                  ))
                                }
                                <Select.Option value={'other'}>其他</Select.Option>
                              </Select>
                            )}
                          </Form.Item>
                        ) : ''
                      }
                      <Form.Item>
                        {getFieldDecorator('channel', { initialValue: null })(
                          <Select style={{ width: 120 }} placeholder={'进线渠道'}>
                            <Select.Option value={null}>进线渠道</Select.Option>
                            <Select.Option value={'web'}>web</Select.Option>
                          </Select>
                        )}
                      </Form.Item>
                      <Form.Item>
                        {getFieldDecorator('search')(
                          <Input placeholder={'请输入用户、会话名称或会话ID'} style={{ width: 260 }} />
                        )}
                      </Form.Item>
                      <Form.Item>
                        <Button type={'primary'} onClick={this.queryByCondition}>查询</Button>
                      </Form.Item>
                      <Form.Item>
                        <Dropdown
                          overlay={menu}
                          placement="bottomCenter"
                          trigger={['click']}
                          onVisibleChange={this.handleVisibleChange}
                          visible={this.state.visible}
                        >
                          <Button icon='control'></Button>
                        </Dropdown>
                      </Form.Item>
                    </div>
                    <Form.Item style={{ margin: 0 }}>
                      <Button onClick={this.exportRecords}>导出</Button>
                    </Form.Item>
                  </div>
                </Form>
              </div>
              <div style={{ margin: '10px 0 0' }}>
                <Table
                  rowKey={'id'}
                  columns={columns}
                  dataSource={list}
                  loading={loading}
                  pagination={false}
                  scroll={{ x: 1000, y: 652 }}
                />
                {total > 10 ? (
                  <Pagination
                    style={{ textAlign: 'right', marginTop: 16 }}
                    total={total}
                    current={queryData.current}
                    onShowSizeChange={this.queryByPage}
                    onChange={this.queryByPage}
                    showSizeChanger={true}
                    pageSizeOptions={['10', '20', '30', '40', '100']}
                  />
                ) : null}
              </div>
              <ContextModal visible={contextModalVisible} message={contextMessage} cancelContextModal={this.cancelContextModal} />
            </Card>
          </PageHeaderWrapper>
        </Suspense>
      </div>
    );
  }
}

export default connect(({ user }) => ({
  currentUser: user.currentUser,
}))(Form.create()(SessionRecords));
